package com.hutiao.snowhb.actions.wechat;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.hutiao.snowhb.common.DateTimeUtil;
import com.hutiao.snowhb.common.MongoUtil;
import com.hutiao.snowhb.entities.PhotographerBean;
import com.hutiao.snowhb.entities.SnowMM;
import com.hutiao.snowhb.entities.SnowMMLocation;
import com.hutiao.snowhb.entities.SnowMMPrebook;
import com.hutiao.snowhb.resource.ConfigInfo;
import com.hutiao.snowhb.service.ChatService;
import com.hutiao.snowhb.service.PhotographerService;
import com.hutiao.snowhb.service.SnowMMService;
import com.hutiao.snowhb.wechat.tools.WeiXinTools;
import com.hutiao.snowhb.wechat.vo.WxRecvTextMsg;
import com.hutiao.snowhb.wechat.vo.WxSendMsg;
import com.hutiao.snowhb.wechat.vo.WxSendNewsMsg;
import com.hutiao.snowhb.wechat.vo.WxSendPicMsg;
import com.hutiao.snowhb.wechat.vo.WxSendTextMsg;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/wechat")
public class HandleTextMsgAction extends ActionSupport implements ServletRequestAware {
	
	private static Logger logger = Logger.getLogger(HandleTextMsgAction.class);

	private static final long serialVersionUID = 1078066254714626458L;

	private HttpServletRequest request;
	
	@Autowired
	private ChatService chatService;

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	private String result;
	
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
	
	@Autowired
	private PhotographerService photographerService;

	public PhotographerService getPhotographerService() {
		return photographerService;
	}

	public void setPhotographerService(PhotographerService photographerService) {
		this.photographerService = photographerService;
	}
	
	@Autowired
	private SnowMMService mmService;

	@Action(value="handletextmsg",
			results = {
				@Result(name="success",type="xmlstr", params={"stringName", "result"}),
				@Result(name="rn_eventmsg", type="chain", location="snowmm/handleeventmsg")})
	public String execute() throws Exception {
		
		logger.info("msg type is WxRecvTextMsg");
		
		WxRecvTextMsg recvMsg = (WxRecvTextMsg) this.request.getAttribute("recvMsg");
		WxSendMsg sendMsg = WeiXinTools.builderSendByRecv(recvMsg);
		
		// 用户输入的内容
		String text = recvMsg.getContent().trim();
		logger.info("text:" + text);

//		if (text.contains("#") || text.contains("＃")) {
//			
//			// 我是摄影师活动的处理
//			
//			String[] temp = text.split("#");
//			if (temp == null || temp.length < 2) {
//				temp = text.split("＃");
//			}
//			if (temp == null || temp.length < 2) {
//				return SUCCESS;
//			}
//			
//			String photoTitle = temp[0];
//			String photoDesc = temp[1];
//			
//			StringBuffer buffer = new StringBuffer();  
//		    buffer.append("感谢您参加“我是摄影师”微信建筑摄影活动。").append("\n\n");
//		    buffer.append("现在您仅需上传建筑摄影作品，即可完成参赛！");
//		    String echo = buffer.toString();
//			String key = "photographer_" + recvMsg.getFromUser();
//			
//			PhotographerBean bean = MongoUtil.findSession(key);
//			bean.setOpenId(recvMsg.getFromUser());
//			bean.setPhotoTitle(photoTitle);
//			bean.setPhotoDesc(photoDesc);
//			
//			if (bean.getPhotoUrl() != null && !bean.getPhotoUrl().equals("")) {
//				try {
//					int photoId = this.photographerService.saveUserPhoto(bean);
//					String redirectUrl = ConfigInfo.hdPhotoDetailUrl+"?photoId="+photoId;
//					echo = "感谢您的参与，您的作品我们已收到。 <a href=\""+redirectUrl+"\">点击查看</a>";
//					MongoUtil.removeSession(key);
//				} catch (Exception e) {
//					logger.error("Exception", e);
//					echo = "对不起，作品保存出现了一点问题，请您稍后再试。";
//				}
//			} else {
//				MongoUtil.saveSession(bean);
//				logger.info("session put ok");
//			}
//			
//			// 返回下一步的操作提示
//			sendMsg = WeiXinTools.builderSendByRecv(recvMsg);
//			sendMsg = new WxSendTextMsg(sendMsg, echo);
//			this.result = WeiXinTools.getSendXmlStr(sendMsg);
//			
//		} else 
		
//		if (text.equals("01")) {
//			// 微园林活动01回复
//			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
//			sendNewsMsg.addItem("“微园林 微分享 赢大奖”活动详情", "分享您拍的“微园林”相片给小伙伴们，就有机会获得雪花为您准备精美礼品，机会多多，丰富好礼等你来抢哦~~点击了解详情！",
//					"http://static.hutiao.me/snow/huodong/weiyuanlin/welcome_01.jpg",
//					"http://mp.weixin.qq.com/s?__biz=MjM5NDA5NDU3Ng==&mid=200296930&idx=1&sn=80c00ac88c0b7833e5662d1d03b458d8#rd");
//			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
//						
//		} else if (text.equals("02")) {
//			// 微园林活动02回复
//			StringBuffer buffer = new StringBuffer();  
//		    buffer.append("/:8-)微园林活动① 需要到活动现场参与互动，目前开展活动地址如下：").append("\n");
//		    buffer.append("武汉地区").append("\n");
//		    buffer.append("1 简朴世家").append("\n");
//		    buffer.append("地址：江岸区三阳路11号（三阳路与胜利街交叉路口）").append("\n");
//		    buffer.append("2 刘胖子").append("\n");
//		    buffer.append("地址：武汉江岸区兴业路191号百步亭花园秀泽园北区26栋(近622终点站)").append("\n");
//		    buffer.append("3 外婆家乡菜").append("\n");
//		    buffer.append("地址：仁和路(近天际万豪酒店)").append("\n");
//		    buffer.append("4 中百仓储墨水湖店").append("\n");
//		    buffer.append("地址：汉阳徐家南湾20号").append("\n");
//		    buffer.append("5 华润苏果后湖店").append("\n");
//		    buffer.append("地址：江岸区后湖大道百步亭花园路路口").append("\n");
//		    buffer.append("宜昌地区 ").append("\n");
//		    buffer.append("1 梁记粥铺 ").append("\n");
//		    buffer.append("地址：宜昌市西陵区西陵一路").append("\n");
//		    buffer.append("2 燕莎酒店").append("\n");
//		    buffer.append("地址：宜昌市西陵区东湖二路").append("\n");
//		    buffer.append("3 国贸香山凤凰城店").append("\n");
//		    buffer.append("地址：夷陵区香山凤凰城小区旁").append("\n");
//		    buffer.append("/:8-)微园林活动②领奖地址将由工作人员微信私信您，请注意查收~").append("\n\n\n");
//
//
//		    buffer.append("/:8-)微园林活动① 需要到活动现场参与互动，目前开展活动地址如下：").append("\n");
//		    buffer.append("恩施地区").append("\n");
//		    buffer.append("1 福厨餐厅").append("\n");
//		    buffer.append("地址 ：恩施州航空路").append("\n");
//		    buffer.append("2 鲁西肥牛").append("\n");
//		    buffer.append("地址 ：恩施州航空路").append("\n");
//		    buffer.append("黄石地区").append("\n");
//		    buffer.append("1 中百仓储文化宫店").append("\n");
//		    buffer.append("地址：黄石大道文化宫").append("\n");
//		    buffer.append("十堰地区").append("\n");
//		    buffer.append("1 寿康生活广场").append("\n");
//		    buffer.append("地址：茅箭区人民南路").append("\n");
//		    buffer.append("鄂州地区").append("\n");
//		    buffer.append("1 鄂州万联购物广场").append("\n");
//		    buffer.append("地址：鄂州城区滨湖路特1号").append("\n");
//		    buffer.append("/:8-)微园林活动②领奖地址将由工作人员微信私信您，请注意查收~").append("\n");
//			
//			sendMsg = new WxSendTextMsg(sendMsg, buffer.toString());
//			this.result = WeiXinTools.getSendXmlStr(sendMsg);
//			
//			
//		} else if (text.equals("03")) {
//			
//			// 微园林活动03回复
//			WxSendNewsMsg sendNewsMsg = new WxSendNewsMsg(sendMsg);
//			sendNewsMsg.addItem(
//							"“微园林 微分享 赢大奖”案例示范",
//							"“微园林 微分享 赢大奖”小伙伴应该怎么参与赢大奖呢？别急，赶紧点击进去了解吧~",
//							"http://static.hutiao.me/snow/huodong/weiyuanlin/welcome_03.jpg",
//							"http://mp.weixin.qq.com/s?__biz=MjM5NDA5NDU3Ng==&mid=200289993&idx=1&sn=f2d5d5523e16b1e34198351256e50f2e#rd");
//			this.result = WeiXinTools.getSendXmlStr(sendNewsMsg);
//			
//		}
		
		if (text.startsWith("我在$")) {
			
			// 啤酒妹上线的第二步
			String openId = recvMsg.getFromUser();
			SnowMM mm = this.mmService.getMMbyOpenId(openId);
			String echo = "";
			
			if (mm != null) {
				SnowMMLocation loca = MongoUtil.findMMCheckinSession(mm.getMmid());
				if (loca == null) {
					// session中没有位置信息
					echo = mm.getNickname() + "你好，请先上传你的位置";
					sendMsg = new WxSendTextMsg(sendMsg, echo);
					this.result = WeiXinTools.getSendXmlStr(sendMsg);
					return SUCCESS;
				}
				
				// 上线操作
				String poi = text.split("\\$")[1];
				this.mmService.mmCheckin(loca.getMmid(), loca.getLatitude(), loca.getLongitude(), loca.getLabel(), poi);
				
				// 删除session
				MongoUtil.removeMMCheckinSession(mm.getMmid());
				
				StringBuffer buffer = new StringBuffer();  
			    buffer.append("操作成功，您现在是‘在线’状态，祝好运！").append("\n\n");
			    buffer.append("回复'我是雪花妹'可以查看您‘收到的订座信息’等资料");
				sendMsg = new WxSendTextMsg(sendMsg, buffer.toString());
				this.result = WeiXinTools.getSendXmlStr(sendMsg);
				return SUCCESS;
			}
			
		} else if (text.equals("雪花妹下线")) {
			
			// 啤酒妹下班
			String openId = recvMsg.getFromUser();
			SnowMM mm = this.mmService.getMMbyOpenId(openId);
			String echo = "";
			
			if (mm == null) {
				// 不是mm
				echo = "你好像还不是雪花妹子哦。";
			} else {
				this.mmService.mmCheckout(mm.getMmid());
				echo = "辛苦了，下班操作成功，来瓶雪花放松一下吧：）";
			}
			
			sendMsg = new WxSendTextMsg(sendMsg, echo);
			this.result = WeiXinTools.getSendXmlStr(sendMsg);
			
		} else if (text.equals("我是雪花妹")) {
			
			// 用于mm查属于自己的订座信息
			String openId = recvMsg.getFromUser();
			SnowMM mm = this.mmService.getMMbyOpenId(openId);
			
			if (mm != null) {
				
				SnowMMLocation loca = this.mmService.getCurrentLocation(mm.getMmid());
				List<SnowMMPrebook> bookList = this.mmService.getPrebookList(mm.getMmid(), 0);
				
				StringBuffer buffer = new StringBuffer();  
				if (loca==null) {
					buffer.append("您目前是‘离线’状态；").append("\n");
				} else {
			    	buffer.append("您目前是‘在线’状态，位置在‘"+loca.getPoi()+"’，上线时间"+DateTimeUtil.Date2String(loca.getCheckinTime(), "MM月dd日 HH:mm")+"；").append("\n");
			    }
				if (bookList == null || bookList.size() == 0) {
					buffer.append("您有0个未处理的订座请求；").append("\n\n");
				} else {
					buffer.append("您有"+bookList.size()+"个未处理的订座请求；").append("\n\n");
				    buffer.append("最近的一个订座请求是：").append("\n");
				    buffer.append("订座时间：" + DateTimeUtil.Date2String(bookList.get(0).getCreateTime(), "MM月dd日 HH:mm")).append("\n");
				    buffer.append("订座位置：" + bookList.get(0).getLoca().getPoi()).append("\n");
				    buffer.append("就餐人数：" + bookList.get(0).getCustNum()).append("\n");
				    if (bookList.get(0).getArriTime() != null) {
				    	buffer.append("预计到店时间：" + bookList.get(0).getArriTime()).append("\n");
				    }
				    buffer.append("订座联系方式：" + bookList.get(0).getCustPhone()).append("\n\n");
				}
				String redirectUrl = ConfigInfo.iamSnowmmUrl + "?mmid="+mm.getMmid();
			    buffer.append("<a href=\""+redirectUrl+"\">查看详情>></a>").append("\n");
			    
			    sendMsg = new WxSendTextMsg(sendMsg, buffer.toString());
				this.result = WeiXinTools.getSendXmlStr(sendMsg);
				return SUCCESS;
			}
			
		} else if (text.equals("爱钢城")) {
			
			sendMsg = new WxSendTextMsg(sendMsg, "雪花啤酒携手钢城引爆夏日激情，感谢您关注“清凉一夏 雪花钢城专享团购”活动。参与活动报名请<a href=\"http://static.hutiao.me/snow/huodong/gctg/index.html\" >点击这里</a>,或点击底部菜单栏【活动专区】查看");
			this.result = WeiXinTools.getSendXmlStr(sendMsg);
			
		} else if (text.equals("果啤获奖")) {
			
			sendMsg = new WxSendTextMsg(sendMsg, "<a href=\"http://mp.weixin.qq.com/s?__biz=MjM5NDA5NDUzMQ==&mid=202288226&idx=1&sn=73ef4d69693c42b6c42c7727871909cb\" >果啤活动7月获奖名单</a>");
			this.result = WeiXinTools.getSendXmlStr(sendMsg);
			
		} else {
			
			//sendMsg = new WxSendTextMsg(sendMsg, recvMsg.getContent());
			//this.result = WeiXinTools.getSendXmlStr(sendMsg);
			
			
			Map<String, Object> msg = chatService.getAutoResponse(recvMsg.getContent());
			
			if (msg == null) {
				sendMsg = new WxSendTextMsg(sendMsg, "So sorry，您发的我暂时还不能理解，如果想了解我们雪花产品，请点击菜单【雪花品牌】->【雪花产品】具体了解。");
				this.result = WeiXinTools.getSendXmlStr(sendMsg);
				return SUCCESS;
			}
			
			String type = msg.get("type").toString();
			String response = msg.get("response").toString();
			
			if (type.equals("1")) {
				sendMsg = new WxSendTextMsg(sendMsg, response);
				this.result = WeiXinTools.getSendXmlStr(sendMsg);
				
			} if (type.equals("2")) {
				sendMsg = new WxSendPicMsg(sendMsg, response);
				this.result = WeiXinTools.getSendXmlStr(sendMsg);
			}
			
//			// simsimi机器人处理
//			String sss = SimsimiClient.chat(text);
//			sendMsg = new WxSendTextMsg(sendMsg, sss);
//			this.result = WeiXinTools.getSendXmlStr(sendMsg);
		}
		
		return SUCCESS;
	}

}
